/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 激活码接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const { ActiveCode, UserActiveExam, Exam } = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, sortModel } = require('@/utils/controllerCommon')

/**
 * 列表查询激活码接口
 * @param {*} ctx
 * @returns
 */
module.exports.listActiveCode = async (ctx) => {
  const { examId } = ctx.query
  const whereCondition = {}
  if (examId !== undefined) {
    whereCondition.examId = examId
  }
  const orderCondition = [['createTime', 'desc']]

  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await ActiveCode.findAndCountAll({
    where: whereCondition,
    include: [
      {
        model: Exam
      },
      {
        model: UserActiveExam
      }
    ],
    offset: +start,
    limit: +pageSize,
    order: orderCondition,
    distinct: true
  })

  // 我们可以给个字段看激活码是否被使用

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

function generateActivationCode(length = 16) {
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length)
    result += characters[randomIndex]
  }
  return result
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 创建激活码接口
 * @param {*} ctx
 */
module.exports.createActiveCode = async (ctx) => {
  const { examId } = ctx.request.body
  // code自动生成
  let code = generateActivationCode()
  // 需要code不重复
  let isExist = await ActiveCode.findOne({
    where: {
      code
    }
  })

  let cnt = 1

  while (isExist && cnt < 5) {
    code = generateActivationCode()
    isExist = await ActiveCode.findOne({
      where: {
        code
      }
    })
    cnt++
  }
  const t = await Mysequelize.transaction()
  const nextId = generatId()
  const sort = await ActiveCode.max('sort')

  let createObj = {
    id: nextId,
    examId,
    code,
    sort: sort + 1,
    createUser: ctx.user.id,
    updateUser: ctx.user.id
  }
  try {
    // 到这里可以进行激活码的添加了,排序字段默认是最大值
    const activeCode = await ActiveCode.create(createObj, {
      transaction: t
    })
    await t.commit()
    const exam = await Exam.findByPk(BigInt(examId))
    ctx.body = R.success({
      code: activeCode.code,
      examName: exam.name
    })
  } catch (error) {
    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.ACTIVE_CODE_CREATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除激活码接口
 * @param {*} ctx
 */
module.exports.delActiveCodes = async (ctx) => {
  await delModel(
    ActiveCode,
    ERROR_USER_CODE.ACTIVE_CODE_DEL_ERROR,
    'activeCodeIds'
  )(ctx, [{ model: UserActiveExam, idName: 'activeCodeId' }])
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 激活码排序接口
 * @param {*} ctx
 */
module.exports.sortActiveCodes = async (ctx) => {
  // 传递的激活码ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    ActiveCode,
    ERROR_USER_CODE.ACTIVE_CODE_SORT_ERROR,
    'activeCodeIds'
  )(ctx)
}
